package main

import (
	"exam_jxk/pkg/server"
	"exam_jxk/pkg/tool"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

var configFile = flag.String("f", "config/server.yml", "set configs file which viper will loading.")

func main() {
	// 读取配置文件
	viper, err := tool.NewConfig(*configFile)
	if err != nil {
		log.Fatalln("config fail ")
		return
	}

	// 解析服务配置信息
	serverConfig, err := tool.NewServerConfig(viper)
	if err != nil {
		log.Fatalln("config fail ")
	}

	// TODO 初始化日志系统
	glogger := tool.NewLogger(serverConfig.LoggerFile, serverConfig.LoggerDebug)
	glogger.Debug("test")
	glogger.Info("config", zap.Any("data", serverConfig)) // 输出配置信息

	// 初始化redis
	redisPool, err := tool.NewRedis(serverConfig.RedisAddr, serverConfig.RedisPassword, serverConfig.RedisDBNum)
	if err != nil {
		glogger.Error("redis 初始化失败")
		return
	} else {
		glogger.Debug("redis 初始化成功")
	}

	//初始化数据库
	db, err := tool.NewDataBase(serverConfig.DataBaseUrl, serverConfig.LoggerDebug)
	if err != nil {
		glogger.Error("init database fail ")
		return
	}

	//构建主服务
	pc := server.NewServer(db, glogger, redisPool, serverConfig)

	//构建http服务
	var g = gin.Default()
	pc.RegisterHttpServer(g)
	glogger.Debug("使用端口 ", zap.Int("port", serverConfig.ServerPort))

	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", serverConfig.ServerPort),
		Handler: g,
	}

	go func() {
		if err :=srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	signal.Reset(syscall.SIGTERM, syscall.SIGINT)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
	select {
	case <-c:
		//pc.SafeClose()
		//os.Exit(0)
	}
	//g.Run(":8848")
	log.Println("exit")
}
